import { ElMessage } from "element-plus";
import type { CascaderProps, Resolve } from "element-plus";
import { onMounted } from "vue";

/**
 * 表格组件基础配置属性
 */
export interface BasicCascaderProps {
  // 是否在创建页面时即调用数据列表接口，默认为true
  autoLoad?: boolean;
  loading?: boolean;
  // 查询条件表单对象，类型为any
  queryForm?: any;
  // 数据列表数组
  dataList?: any[];
  // 数据列表查询接口api方法，接收任意数量参数，返回Promise
  queryFunction?: (...arg: any) => Promise<any>;
  //是否懒加载子节点
  lazy?: boolean;
  // 排序字段数组
  descs?: string[];
  // 排序方式数组
  ascs?: string[];
  // props属性对象，类型为any
  props: CascaderProps;
  //节点数据属性，类型为any
  dataProps?: any;
  // 回调事件，类型为any
  onLoaded?: (dataList?: any[]) => void;
}

// let treeRef = null;

export function useCascader(options?: BasicCascaderProps) {
  const queryLazyLoad = (node: Node, resolve: Resolve) => {
    const value = node["data"][instance.props.value];
    if (value) {
      const queryParams = {};
      queryParams[instance.dataProps.pid] = value;
      queryParams["ascs"] = instance.ascs.join(",");
      queryParams["descs"] = instance.descs.join(",");
      if (instance.queryFunction) {
        instance
          .queryFunction(queryParams)
          .then(res => {
            if (res && res.code === 200) {
              resolve(res.data);
            } else {
              resolve([]);
            }
          })
          .catch(() => {
            resolve([]);
          });
      }
    }
  };

  // if (refObject) {
  //   treeRef = refObject;
  // }
  const defaultOptions: BasicCascaderProps = {
    // 是否需要自动请求创建接口来获取表格数据，默认为true
    autoLoad: true,
    loading: false,
    //是否懒加载子节点
    lazy: false,
    // 查询表单对象，用于提交条件查询时的参数传递，默认为空对象
    queryForm: {},
    // 表格展示的数据数组，默认为空数组
    dataList: [],
    // 分页组件属性配置，如当前页码、每页展示数据条数等，默认值为 {current:1, size:10,total:0,pageSizes:[1, 10, 20, 50, 100, 200],layout:'total, sizes, prev, pager, next, jumper'}
    props: {
      expandTrigger: "click",
      multiple: false,
      checkStrictly: false,
      emitPath: true,
      lazy: false,
      lazyLoad: queryLazyLoad,
      value: "value",
      label: "label",
      children: "children",
      disabled: "disabled",
      leaf: "leaf",
      hoverThreshold: 500
    } as unknown as CascaderProps,
    dataProps: {
      pid: "pid"
    },
    // 排序时使用的字段名数组，如 ['id','name']，默认为空数组
    descs: [],
    // 排序方向数组，如 ['asc', 'desc']，默认为空数组
    ascs: []
  };

  /**
   * 合并默认属性配置和自定义属性配置
   * @param options 默认属性配置对象
   * @param props 自定义属性配置对象
   * @returns 合并后的属性配置对象
   */
  const mergeDefaultOptions = (defaultOptions: any, options: any): BasicCascaderProps => {
    for (const key in defaultOptions) {
      if (key !== "props") {
        if (!Object.getOwnPropertyDescriptor(options, key)) {
          options[key] = defaultOptions[key];
        }
      } else {
        if (!Object.getOwnPropertyDescriptor(options, key)) {
          options["props"] = defaultOptions[key];
        } else {
          const optionProps = options["props"];
          for (const propsKey in defaultOptions["props"]) {
            if (!Object.getOwnPropertyDescriptor(optionProps, propsKey)) {
              optionProps[propsKey] = defaultOptions["props"][propsKey];
            }
          }
          options.props = optionProps;
        }
      }
    }
    for (const key in options.queryForm) {
      initQueryForm[key] = options.queryForm[key];
    }
    return options;
  };

  const initQueryForm = {};

  // 覆盖默认值
  const instance = mergeDefaultOptions(defaultOptions, options);

  /**
   * 发起分页查询，并设置表格数据和分页信息
   */
  const query = async () => {
    // 判断是否存在instance.queryFunction属性
    if (instance.queryFunction) {
      try {
        instance.loading = true;
        // 调用instance.queryFunction方法发起查询
        await instance
          .queryFunction({
            ...instance.queryForm,
            descs: instance.descs.join(","),
            ascs: instance.ascs.join(",")
          })
          .then(res => {
            if (res.code === 200) {
              // 设置表格展示的数据数组
              instance.dataList = res.data;
              // 执行回调事件
              if (instance.onLoaded) instance.onLoaded(instance.dataList);
            }
          });
      } catch (err: any) {
        // 捕获异常并显示错误提示
        ElMessage.error(err);
      } finally {
        // 结束加载数据，设置instance.loading为false
        instance.loading = false;
      }
    }
  };

  onMounted(() => {
    if (instance.autoLoad) {
      query();
    }
  });

  /**
   * 获取数据列表，并可选择是否刷新当前页码
   * 刷新后不跳转第一页，则入参 getDataList(false)
   * @param refresh 是否刷新当前页码
   */
  const queryCascaderData = () => {
    // 再次发起查询操作
    query();
  };

  const handleResetQuery = () => {
    for (const key in initQueryForm) {
      instance.queryForm[key] = initQueryForm[key];
    }
    query();
  };

  return {
    instance,
    queryCascaderData,
    queryLazyLoad,
    handleResetQuery
  };
}
